<template>
  <div>
    <div>一级：表示能否访问某个页面； 二级：表示能点击某个按钮</div>
    <el-tree
      ref="tree"
      :data="list"
      :props="{label:'name'}"
      show-checkbox
      default-expand-all
      :check-strictly="true"
      node-key="id"
    />

    <div style="text-align: right;">
      <el-button @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { tranListToTreeData } from '@/utils/index.js'
import { getPermissionList } from '@/api/permission.js'
import { getRoleDetail, assignPerm } from '@/api/settings.js'
export default {
  props: { curId: { type: String, default: '' }},
  data() {
    return { list: [] }
  },
  created() {
    this.loadPermissionList() // 获取所有的权限数据

    this.loadRoleDetail() // 获取已有的权限数据
  },
  methods: {
    // 获取已有的权限数据
    async loadRoleDetail() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log('角色已经具备的权限是:', res.data.permIds)

        // tree组件.setCheckedKeys([]) : 让节点处于选中状态
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log('getRoleDetail', err)
      }
    },
    // 获取所有的权限数据
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        // 保存数据
        // 格式转换：数组--》tree

        this.list = tranListToTreeData(res.data)
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },

    hCancel() {
      this.$emit('close')
    },
    async hSubmit() {
      try {
        // 如何获取tree中选中的节点？this.$refs.tree.getCheckedKeys()
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPerm({ id: this.curId, permIds })
        console.log(res)
        this.$message.success('操作成功')
      } catch (err) {
        console.log('getPermissionList', err)
      }
    }
  }
}
</script>
